<template>
  <div class="crm-customer-profile">
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading"><i class="el-icon-loading" /></el-icon>
      <span>加载客户画像中...</span>
    </div>

    <div v-else-if="categories.length === 0" class="empty-state">
      <i class="el-icon-user" />
      <h3>暂无画像配置</h3>
      <p>请先在画像管理中配置分类和参数</p>
    </div>

    <div v-else class="profile-content">
      <div class="profile-header">
        <div class="customer-info">
          <h3>{{ customerName }} 的客户画像</h3>
          <div class="customer-meta">
            <span class="customer-id">ID: {{ crmcustomer_id }}</span>
            <div v-if="statistics" class="profile-statistics">
              <el-tag
                v-if="statistics.green_line_count > 0"
                type="success"
                size="mini"
              >
                <i class="el-icon-circle-check" /> 绿线: {{ statistics.green_line_count }}
              </el-tag>
              <el-tag
                v-if="statistics.red_line_count > 0"
                type="danger"
                size="mini"
              >
                <i class="el-icon-warning" /> 红线: {{ statistics.red_line_count }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="profile-actions">
          <el-button
            type="primary"
            size="small"
            :loading="saving"
            @click="handleSave"
          >
            <i class="el-icon-check" /> 保存画像
          </el-button>
          <el-button
            type="info"
            size="small"
            @click="handleReset"
          >
            <i class="el-icon-refresh" /> 重置
          </el-button>
        </div>
      </div>

      <div class="profile-form">
        <div
          v-for="category in categories"
          :key="category.id"
          class="profile-row"
        >
          <div class="category-label">
            {{ category.name }}:
          </div>

          <div class="parameter-selector">
            <el-select
              v-model="profileData[category.id].parameter_id"
              placeholder="选择参数"
              clearable
              style="width: 200px"
              @change="handleParameterChange(category.id)"
            >
              <el-option
                v-for="param in category.parameters"
                :key="param.id"
                :label="param.name"
                :value="param.id"
              >
                <span>{{ param.name }}</span>
                <el-tag
                  :type="getParamTypeColor(param.param_type)"
                  size="mini"
                  style="float: right; margin-left: 10px"
                >
                  {{ getParamTypeDisplay(param.param_type) }}
                </el-tag>
              </el-option>
            </el-select>
            <!-- 参数类型颜色指示器 -->
            <div
              v-if="profileData[category.id].parameter_id"
              :class="['param-type-indicator', getSelectedParameterIndicatorClass(category.id)]"
            >
              <i v-if="getSelectedParameterType(category.id) === 'green_line'" class="el-icon-circle-check" />
              <i v-else-if="getSelectedParameterType(category.id) === 'red_line'" class="el-icon-warning" />
              <i v-else class="el-icon-info" />
            </div>
          </div>

          <div class="value-input">
            <el-input
              v-model="profileData[category.id].value"
              placeholder="实际数值"
              :disabled="!profileData[category.id].parameter_id"
              style="width: 300px"
              @input="handleValueChange(category.id)"
            />
          </div>

          <div v-if="profileData[category.id].id" class="profile-meta">
            <el-tooltip placement="top">
              <div slot="content">
                <div>最后更新: {{ profileData[category.id].update_at | formatDate }}</div>
                <div v-if="profileData[category.id].verified">
                  已验证: {{ profileData[category.id].verified_by_name }}
                </div>
              </div>
              <el-tag
                :type="profileData[category.id].verified ? 'success' : 'info'"
                size="mini"
              >
                {{ profileData[category.id].verified ? '已验证' : '未验证' }}
              </el-tag>
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import {
  GetCRMCustomerProfileCategory,
  GetCRMCustomerProfileParameter,
  GetCRMCustomerProfile,
  PostCRMCustomerProfile,
  PutCRMCustomerProfile,
  DeleteCRMCustomerProfile
} from '@/api/crm/crmcustomerprofile'

export default {
  name: 'CRMCustomerProfile',
  filters: {
    formatDate(value) {
      if (!value) return ''
      const date = new Date(value)
      return date.toLocaleString()
    }
  },
  props: {
    crmcustomer_id: {
      type: [String, Number],
      required: true
    },
    customerName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      saving: false,
      categories: [], // 分类和参数选项
      profileData: {}, // 画像数据 {categoryId: {id, parameter_id, value, ...}}
      originalData: {}, // 原始数据用于比较
      statistics: null // 画像统计信息
    }
  },
  computed: {
    hasChanges() {
      return Object.keys(this.profileData).some(categoryId => {
        const current = this.profileData[categoryId]
        const original = this.originalData[categoryId]

        return current.parameter_id !== original.parameter_id ||
               current.value !== original.value
      })
    }
  },
  watch: {
    crmcustomer_id: {
      handler(newVal) {
        if (newVal) {
          this.loadCustomerProfile()
        }
      },
      immediate: true
    }
  },
  methods: {
    // 加载客户画像数据
    async loadCustomerProfile() {
      if (!this.crmcustomer_id) return

      this.loading = true
      try {
        // 1. 获取所有分类和参数选项
        await this.loadCategoriesAndParameters()

        // 2. 获取客户现有的画像数据
        await this.loadExistingProfiles()
      } catch (error) {
        console.error('加载客户画像失败:', error)
        this.$message.error('加载客户画像失败')
      } finally {
        this.loading = false
      }
    },

    // 获取分类和参数选项
    async loadCategoriesAndParameters() {
      // 获取所有分类
      const categoryResponse = await GetCRMCustomerProfileCategory('', 'pageSize=1000')
      if (!categoryResponse.success) {
        throw new Error('获取分类失败')
      }

      const categories = categoryResponse.data.data || []

      // 为每个分类获取可选参数
      for (const category of categories) {
        const paramResponse = await GetCRMCustomerProfileParameter('', `category_id=${category.id}&pageSize=1000`)
        if (paramResponse.success) {
          category.parameters = paramResponse.data.data || []
        } else {
          category.parameters = []
        }
      }

      this.categories = categories.filter(cat => cat.parameters.length > 0)

      // 初始化画像数据结构
      this.initializeProfileData()
    },

    // 初始化画像数据结构
    initializeProfileData() {
      const profileData = {}
      const originalData = {}

      this.categories.forEach(category => {
        profileData[category.id] = {
          id: null,
          category_id: category.id,
          parameter_id: '',
          value: '',
          verified: false,
          verified_by_name: '',
          update_at: ''
        }
        originalData[category.id] = { ...profileData[category.id] }
      })

      this.profileData = profileData
      this.originalData = originalData
    },

    // 获取客户现有画像数据
    async loadExistingProfiles() {
      try {
        const response = await GetCRMCustomerProfile('', `customer_id=${this.crmcustomer_id}&profile_summary=true`)
        if (response.success && response.data) {
          console.log('获取到的画像数据:', response.data)

          // 保存统计信息
          if (response.data._statistics) {
            this.statistics = response.data._statistics
          }

          // 新的数据格式：按分类名称分组
          Object.keys(response.data).forEach(categoryName => {
            if (categoryName === '_statistics') return // 跳过统计数据

            const categoryData = response.data[categoryName]
            const categoryId = categoryData.category_id

            if (this.profileData[categoryId] && categoryData.parameters && categoryData.parameters.length > 0) {
              // 取第一个参数作为该分类的画像数据（通常每个分类只有一个参数实例）
              const profileParam = categoryData.parameters[0]

              // 通过参数名称找到对应的参数ID
              const category = this.categories.find(cat => cat.id === categoryId)
              if (category) {
                const parameter = category.parameters.find(param => param.name === profileParam.parameter_name)
                if (parameter) {
                  this.profileData[categoryId] = {
                    id: profileParam.id,
                    category_id: categoryId,
                    parameter_id: parameter.id,
                    value: profileParam.value || '',
                    verified: profileParam.verified,
                    verified_by_name: profileParam.verified_by_name || '',
                    update_at: profileParam.update_at
                  }
                  this.originalData[categoryId] = { ...this.profileData[categoryId] }
                }
              }
            }
          })

          this.$forceUpdate()
        }
      } catch (error) {
        console.error('获取客户画像数据失败:', error)
      }
    },

    // 参数选择变更
    handleParameterChange(categoryId) {
      const profileItem = this.profileData[categoryId]

      // 如果清空了参数选择，也清空值
      if (!profileItem.parameter_id) {
        profileItem.value = ''
      }
    },

    // 值变更
    handleValueChange(categoryId) {
      // 触发计算属性重新计算
      this.$forceUpdate()
    },

    // 获取参数类型颜色
    getParamTypeColor(paramType) {
      switch (paramType) {
        case 'green_line':
          return 'success'
        case 'red_line':
          return 'danger'
        case 'normal':
        default:
          return 'info'
      }
    },

    // 获取参数类型显示文本
    getParamTypeDisplay(paramType) {
      switch (paramType) {
        case 'green_line':
          return '绿线'
        case 'red_line':
          return '红线'
        case 'normal':
        default:
          return '正常'
      }
    },

    // 处理保存
    async handleSave() {
      console.log('开始保存，hasChanges:', this.hasChanges)
      console.log('profileData:', this.profileData)
      console.log('originalData:', this.originalData)

      // 临时注释掉，强制执行保存
      // if (!this.hasChanges) {
      //   this.$message.info('没有需要保存的变更')
      //   return
      // }

      this.saving = true
      try {
        // 准备批量提交的数据
        const batchData = []
        const deleteIds = []

        Object.keys(this.profileData).forEach(categoryId => {
          const current = this.profileData[categoryId]
          const original = this.originalData[categoryId]

          console.log(`分类${categoryId} - 当前:`, current, '原始:', original)

          if (current.parameter_id !== original.parameter_id || current.value !== original.value) {
            if (!original.id && current.parameter_id) {
              // 新增 - 只要有参数ID就可以新增，值可以为空
              console.log('准备新增:', categoryId, current)
              batchData.push({
                customer_id: this.crmcustomer_id,
                category_id: categoryId,
                parameter_id: current.parameter_id,
                value: current.value || '' // 确保值不为undefined
              })
            } else if (original.id && current.parameter_id) {
              // 修改 - 只要有参数ID就可以修改，值可以为空
              console.log('准备修改:', categoryId, current)
              batchData.push({
                id: original.id,
                customer_id: this.crmcustomer_id,
                category_id: categoryId,
                parameter_id: current.parameter_id,
                value: current.value || '', // 确保值不为undefined
                _method: 'PUT'
              })
            } else if (original.id && !current.parameter_id) {
              // 删除 - 只有当参数ID被清空时才删除
              console.log('准备删除:', categoryId, original.id)
              deleteIds.push(original.id)
            }
          }
        })

        console.log('准备执行操作 - 删除:', deleteIds, '批量数据:', batchData)

        // 执行删除操作
        for (const id of deleteIds) {
          console.log('执行删除，ID:', id)
          const response = await DeleteCRMCustomerProfile(id)
          console.log('删除响应:', response)
          // 清空本地数据
          const categoryId = Object.keys(this.profileData).find(cId => {
            return this.profileData[cId].id === id
          })
          if (categoryId) {
            this.profileData[categoryId].id = null
            this.profileData[categoryId].parameter_id = ''
            this.profileData[categoryId].value = ''
            this.profileData[categoryId].verified = false
            this.profileData[categoryId].verified_by_name = ''
            this.profileData[categoryId].update_at = ''
          }
        }

        // 分离新增和修改数据
        const createData = batchData.filter(item => !item._method)
        const updateData = batchData.filter(item => item._method === 'PUT')

        // 批量新增
        if (createData.length > 0) {
          console.log('执行批量新增，数据:', createData)
          const response = await PostCRMCustomerProfile(createData)
          console.log('批量新增响应:', response)
          if (response.success && response.data) {
            // 如果是批量创建，response.data.created_profiles包含创建的数据
            if (response.data.created_profiles) {
              response.data.created_profiles.forEach(item => {
                // 更新本地数据的ID
                const categoryId = Object.keys(this.profileData).find(cId => {
                  const profile = this.profileData[cId]
                  return !profile.id && profile.parameter_id === item.data.parameter_id
                })
                if (categoryId) {
                  this.profileData[categoryId].id = item.data.id
                }
              })
            } else if (response.data.id) {
              // 单个创建的情况
              const categoryId = Object.keys(this.profileData).find(cId => {
                const profile = this.profileData[cId]
                return !profile.id && profile.parameter_id === response.data.parameter_id
              })
              if (categoryId) {
                this.profileData[categoryId].id = response.data.id
              }
            }
          }
        }

        // 单独处理修改
        for (const item of updateData) {
          const { id, ...data } = item
          delete data._method
          console.log('执行修改，ID:', id, '数据:', data)
          const response = await PutCRMCustomerProfile(id, data)
          console.log('修改响应:', response)
        }

        this.$message.success('客户画像保存成功')

        // 更新原始数据为当前数据，避免重复提交
        Object.keys(this.profileData).forEach(categoryId => {
          this.originalData[categoryId] = { ...this.profileData[categoryId] }
        })

        // 重新加载数据以更新统计信息
        await this.loadExistingProfiles()
      } catch (error) {
        console.error('保存客户画像失败:', error)
        let errorMessage = '保存失败'
        if (error.response && error.response.data && error.response.data.msg) {
          errorMessage += '：' + error.response.data.msg
        }
        this.$message.error(errorMessage)
      } finally {
        this.saving = false
      }
    },

    // 重置数据
    handleReset() {
      this.$confirm('确认重置所有未保存的变更吗？', '重置确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 重新加载原始数据
        this.loadExistingProfiles()
        this.$message.success('已重置所有变更')
      })
    },

    // 根据ID查找参数
    findParameterById(parameterId) {
      for (const category of this.categories) {
        const parameter = category.parameters.find(p => p.id === parameterId)
        if (parameter) return parameter
      }
      return null
    },

    // 获取选中参数的类型
    getSelectedParameterType(categoryId) {
      const parameterId = this.profileData[categoryId].parameter_id
      if (!parameterId) return ''

      const parameter = this.findParameterById(parameterId)
      return parameter ? parameter.param_type : ''
    },

    // 获取选中参数指示器的样式类
    getSelectedParameterIndicatorClass(categoryId) {
      const paramType = this.getSelectedParameterType(categoryId)
      switch (paramType) {
        case 'green_line':
          return 'param-indicator-green'
        case 'red_line':
          return 'param-indicator-red'
        case 'normal':
        default:
          return 'param-indicator-normal'
      }
    }
  }
}
</script>

<style scoped>
.crm-customer-profile {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px;
  color: #909399;
}

.loading-container .el-icon-loading {
  font-size: 32px;
  margin-bottom: 15px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px;
  color: #909399;
}

.empty-state i {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-state h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
}

.profile-content {
  padding: 0;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e6e6e6;
  background: #fafbfc;
}

.customer-info h3 {
  margin: 0 0 5px 0;
  font-size: 18px;
  color: #303133;
}

.customer-meta {
  display: flex;
  align-items: center;
  gap: 15px;
}

.customer-id {
  font-size: 12px;
  color: #909399;
}

.profile-statistics {
  display: flex;
  gap: 8px;
  align-items: center;
}

.profile-statistics .el-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

.profile-actions {
  display: flex;
  gap: 10px;
}

.profile-form {
  padding: 20px;
}

.profile-row {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #fafbfc;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
}

.profile-row:last-child {
  margin-bottom: 0;
}

.category-label {
  width: 120px;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  text-align: right;
  padding-right: 15px;
  flex-shrink: 0;
}

.parameter-selector {
  margin-right: 15px;
  flex-shrink: 0;
  position: relative;
  display: flex;
  align-items: center;
}

/* 参数类型指示器 */
.param-type-indicator {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  pointer-events: none;
  z-index: 10;
}

.param-indicator-green {
  color: #67C23A;
}

.param-indicator-red {
  color: #F56C6C;
}

.param-indicator-normal {
  color: #409EFF;
}

.value-input {
  flex: 1;
  margin-right: 15px;
}

.profile-meta {
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-row {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .category-label {
    width: 100%;
    text-align: left;
    padding-right: 0;
    margin-bottom: 5px;
  }

  .parameter-selector,
  .value-input {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }

  .profile-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .profile-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
